<template>
  <div>
    <page-dialog
      v-show="mountingsUseInfo.visible"
      :title="mountingsUseInfo.title"
      v-model:visible="mountingsUseInfo.visible"
      :width="mountingsUseInfo.width"
      :bt-loading="mountingsUseInfo.btLoading"
      :bt-list="mountingsUseInfo.btList"
      @reset="reset"
    >
      <NewPageFilter
        v-model:query="mountingsUseInfo.filterInfo.query"
        :filter-btn="mountingsUseInfo.filterInfo.list"
      >
        <template v-slot:filter-removeMountings>
          <el-button
            :disabled="!mountingsUseInfo.tableInfo.selections.length"
            @click="removeMountings(undefined)"
            >删除</el-button
          >
        </template>
      </NewPageFilter>
      <el-form
        :model="mountingsUseInfo.tableInfo"
        ref="tableForm"
        style="width: 100%"
      >
        <!-- 表格 -->
        <dialog-table
          ref="mountingsUseTable"
          :refresh="mountingsUseInfo.tableInfo.refresh"
          :init-curpage="mountingsUseInfo.tableInfo.initCurpage"
          v-model:data="mountingsUseInfo.tableInfo.data"
          :api="mountingsUseInfo.tableInfo.api"
          :query="mountingsUseInfo.tableInfo.query"
          :pager="true"
          :tabIndex="true"
          :field-list="mountingsUseInfo.tableInfo.fieldList"
          :handle="mountingsUseInfo.tableInfo.handle"
          :row-class-name="mountingsUseInfo.tableRowClassName"
          @handleEvent="selectMountingsTable"
        >
          <template v-slot:col-price="scope">
            <el-form-item
              :prop="`data.${scope.$index}.price`"
              :rules="scope.$index >= 0 ? [
                {
                  validator: $validate.positiveMoneyNoZeroAsset,
                  trigger: ['blur', 'change'],
                },
                {
                  required: scope.$index >= 0,
                  message: '请输入单价',
                  trigger: 'blur',
                },
              ] : []"
            >
              <el-input-number
                style="width: 100%; margintop: 18px"
                v-model.lazy="scope.row.price"
                clearable
                controls-position="right"
                :precision="
                  $store.state.permission.systemConfig.assets_price_precision
                "
                @change="changePrice($event, scope.row, `price`)"
                :min="0"
                :max="999999999999999"
              />
            </el-form-item>
          </template>
          <template v-slot:col-qty="scope">
            <el-form-item
              :prop="`data.${scope.$index}.qty`"
              :rules="scope.$index >= 0 ? [
                {
                  validator: $validate.positiveNoAsset,
                  trigger: ['blur', 'change'],
                },
                {
                  required: scope.$index >= 0,
                  message: '请输入数量',
                  trigger: 'blur',
                },
              ] : []"
            >
              <el-input-number
                style="width: 100%; margintop: 18px"
                v-model.lazy="scope.row.qty"
                clearable
                controls-position="right"
                :precision="2"
                @change="changePrice($event, scope.row, `qty`)"
                :min="0"
                :max="999999999999999"
              />
            </el-form-item>
          </template>
          <template v-slot:col-replaceTime="scope">
            <el-form-item
              :prop="`data.${scope.$index}.replaceTime`"
              :rules="scope.$index >= 0 ? [
                {
                  validator: validateUseTime,
                  trigger: 'blur',
                },
                {
                  required: scope.$index >= 0,
                  message: '请选择更换日期',
                  trigger: 'change',
                },
              ] : []"
            >
              <el-date-picker
                v-model="scope.row.replaceTime"
                type="date"
                value-format="YYYY-MM-DD"
                placeholder="选择日期"
              ></el-date-picker>
            </el-form-item>
          </template>
        </dialog-table>
      </el-form>
    </page-dialog>
    <!-- 选择配件 -->
    <SelectAccessories
      v-if="accessoriesInfo.visible"
      v-model:show-dialog="accessoriesInfo.visible"
      :query="accessoriesInfo.query"
      :tableKey="accessoriesInfo.tableKey"
      @callback="changeAccessories"
    />
  </div>
</template>
<script setup name="mountingsUse">
import PageDialog from '@/components/PageDialog/index'
import DialogTable from '@/components/DialogTable/index'

import {
  clearDeviceMaintenanceTaskAccessories,
  getDeviceMaintenanceTaskAccessoriesCustomizeListPage,
  saveDeviceMaintenanceTaskAccessoriesList,
} from '@/api/repair.js'
import { getCustomizeSetting } from '@/api/customize'
import SelectAccessories from '@/components/SelectAccessories/index'
import moment from 'moment'

const { proxy } = getCurrentInstance()
const emit = defineEmits()
const props = defineProps(['visible', 'row'])

//选择配件
const accessoriesInfo = reactive({
  visible: false,
  tableKey:
    'accessoriesArchivesDialog-com.slip.spd.entity.vo.asset.settings.AccessoriesArchivesVO',
  query: {
    id: {
      queryType: 'NOT_IN',
      queryCategory: 'AND',
      value: '',
    },
  },
})
//配件使用相关
const mountingsUseInfo = reactive({
  orderId: '',
  visible: false,
  title: '配件使用',
  btLoading: false,
  type: '',
  msg: '',
  width: '75%',
  flag: true,
  btList: [
    {
      label: '关闭',
      event: handleCloseMountingsUse,
      show: true,
    },
    {
      label: '保存',
      type: 'primary',
      event: saveMountingsUse,
      show: true,
    },
  ],
  // 过滤相关配置
  filterInfo: {
    query: {
      customizeUserVO: {},
      queryMap: {},
    },
    list: [
      {
        label: '添加',
        type: 'button',
        event: addMountings,
        show: true,
      },
      {
        label: '删除',
        type: 'slot',
        value: 'removeMountings',
      },
    ],
  },
  // 表格相关
  tableInfo: {
    refresh: 1,
    initCurpage: 1,
    data: [],
    selections: [],
    api: null,
    query: {
      customizeUserVO: {},
      queryMap: {
        orderId: {
          queryType: 'EQUALS',
          queryCategory: 'AND',
          columnName: '`order_id`',
          queryResource: 0,
          value: props.row.id,
        },
      },
    },
    // query: {
    //   // orderType: 53,
    //   orderId: "",
    //   sort: "create_time desc",
    // },
    fieldList: [],
    handle: {
      fixed: 'right',
      label: '操作',
      width: '50',
      btList: [
        {
          label: '删除',
          event: removeMountings,
          popconfirmText: '删除后将改变数据,是否继续？',
          show: true,
        },
      ],
    },
  },
})

const showDialog = computed({
  get() {
    return props.visible
  },
  set(newValue) {
    emit('update:visible', newValue) // 更新父组件visible
  },
})

watch(
  () => props.visible,
  (newVal) => {
    mountingsUseInfo.visible = newVal
    accessoriesInfo.visible = false
  },
  {
    immediate: true,
  }
)
watch(
  () => props.row,
  (newVal) => {
    mountingsUseInfo.tableInfo.query.queryMap.orderId.value = newVal.id
  },
  {
    immediate: true,
  }
)
watch(
  () => mountingsUseInfo.tableInfo.data,
  (val) => {
    if (val.length) {
      let ids = []
      val.forEach((row) => {
        ids.push(row.productId)
      })
      accessoriesInfo.query.id.value = String(ids)
      if (proxy.$refs.mountingsUseTable) {
        proxy.$refs.mountingsUseTable.setListInfoTotal(val.length)
      }
    } else {
      accessoriesInfo.query.id.value = ''
      if (proxy.$refs.mountingsUseTable) {
        proxy.$refs.mountingsUseTable.setListInfoTotal(0)
      }
    }
  },
  {
    deep: true,
  }
)

let obj = {
  price: {
    label: '单价',
    value: 'price',
    componentType: 'price',
    type: 'slot',
    formatter: proxy.$fn.TripartiteMethodAsset,
    show: false,
    hidden: true,
  },
  qty: {
    label: '数量',
    value: 'qty',
    type: 'slot',
    componentType: 'number',
    formatter: proxy.$fn.TripartiteMethodAsset,
    show: false,
    hidden: true,
  },
  preUnitValue: {
    label: '计量单位',
    value: 'preUnitValue',
    componentType: 'input',
    type: 'column',
    show: false,
    hidden: true,
  },
  replaceTime: {
    label: '更换日期',
    value: 'replaceTime',
    componentType: 'input',
    show: false,
    type: 'slot',
    hidden: true,
  },
  sumAmount: {
    label: '金额',
    value: 'sumAmount',
    componentType: 'price',
    type: 'column',
    formatter: proxy.$fn.TripartiteMethodAsset,
    show: false,
    hidden: true,
  },
}
mountingsUseInfo.tableInfo.fieldList = Object.values({
  ...proxy.$fn.deepClone(proxy.$fieldfList.FieldList),
  ...obj,
})
getCustomize()

function changePrice(e, row, str) {
  if (str === 'qty') {
    row.sumAmount = proxy.$fn.accMul(e, row.price)
  } else if (str === 'price') {
    row.sumAmount = proxy.$fn.accMul(e, row.qty)
  }
  console.log(e, row, str, 'e, row,data')
}
function validateUseTime(rule, value, callback) {
  let currentTime = moment(new Date()).format('YYYY-MM-DD HH:mm:ss')
  if (value > currentTime) {
    callback(new Error('更换日期不能大于当前时间！'))
  } else {
    callback()
  }
}

function reset() {
  emit('callbackMountingsUse', false)
}
//配件使用保存
function saveMountingsUse() {
  // console.log(props.row);
  let data = mountingsUseInfo.tableInfo.data
  if (data.length) {
    proxy.$refs['tableForm'].validate((valid) => {
      console.log(valid, 'valid')
      if (valid) {
        let arr = []

        data.forEach((item) => {
          arr.push({
            productId: item.productId,
            calcQty: item.qty,
            qty: item.qty,
            orderId: props.row.id,
            price: item.price,
            sumAmount: item.sumAmount,
            replaceTime: item.replaceTime,
          })
        })
        saveDeviceMaintenanceTaskAccessoriesList(arr).then((resp) => {
          if (resp && resp.success) {
            emit('callbackMountingsUse', false)
          }
          // mountingsUseInfo.visible = false;
        })
      }
    })
  } else {
    let data = {
      orderId: props.row.id,
    }
    clearDeviceMaintenanceTaskAccessories(data).then((resp) => {
      if (resp && resp.success) {
        emit('callbackMountingsUse', false)
      }
    })
  }
}
//选择配件
function changeAccessories(data) {
  console.log(data, '-------------------选择配件')
  if (data.length) {
    data.forEach((item) => {
      let obj = {
        productId: item.id,
        preCommonName: item.commonName,
        preStandard: item.standard,
        preUnitValue: item.unitName,
        price: item.referencePrice,
        ...item,
      }
      mountingsUseInfo.tableInfo.data.push(obj)
    })
    accessoriesInfo.visible = false
  }
}
function selectMountingsTable(event, data) {
  switch (event) {
    case 'tableCheck':
      mountingsUseInfo.tableInfo.selections = [...data]
      break
  }
}
function handleCloseMountingsUse() {
  emit('callbackMountingsUse', false)
}
//添加配件
function addMountings() {
  accessoriesInfo.visible = true
}
function getMountingsUseList() {
  mountingsUseInfo.tableInfo.refresh = Math.random()
}
//删除配件
function removeMountings(row = undefined) {
  if (row) {
    mountingsUseInfo.tableInfo.data = mountingsUseInfo.tableInfo.data.filter(
      (item) => item.productId !== row.productId
    )
  } else {
    mountingsUseInfo.tableInfo.data = mountingsUseInfo.tableInfo.data.filter(
      (row) => {
        return !mountingsUseInfo.tableInfo.selections.includes(row)
      }
    )
  }
}
function getCustomize() {
  let tableInfo = mountingsUseInfo.tableInfo
  let param = {
    tableKey:
      'deviceMaintenanceTaskAccessoriesList-com.slip.spd.entity.domain.device.maintenance.task.DeviceMaintenanceTaskAccessories',
  }
  tableInfo.isSysGroup = false
  getCustomizeSetting(param).then((res) => {
    if (res && res.success) {
      let data = res.data
      tableInfo.fieldList = proxy.$fn.setFieldList(
        tableInfo.fieldList,
        data.detail
      )
      for (let key in data.detail) {
        if (data.detail[key].sysGroupLevel > 0) {
          tableInfo.isSysGroup = true
        }
      }
      mountingsUseInfo.tableInfo.query.customizeUserVO = data
      tableInfo.api = getDeviceMaintenanceTaskAccessoriesCustomizeListPage
      getMountingsUseList()
    }
  })
}
</script>
